<?php

namespace app\api1\controller;
use hg\apidoc\annotation as Apidoc;
class RobotApi extends Auth
{

    /**
     * @Apidoc\Title("新增机器人接口")
     * @return \think\response\Json|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add()
    {
        $member_id = $this->request->uid;

        $robot_id = input('robot_id', 0, 'intval');
        if(!$robot_id){
            return error('机器人id不能为空！');
        }
        $robot = \app\common\model\Robot::where('id', $robot_id)
            ->where('member_id', $member_id)
            ->find();
        if(!$robot){
            return error('该机器人不存在！');
        }
        $name = input('name', '', 'trim');
        if(!$name){
            return error('名称不能为空！');
        }

        $api = \app\common\model\RobotApi::create([
            'robot_id' => $robot_id,
            'name' => $name,
        ]);
        $api->key = md5($api->id . 'robot_api' . time());
        $api->save();
        return success();

    }


    /**
     * @Apidoc\Title("列表")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("id", type="int", require=true, desc="事件id")
     * @Apidoc\Returned("data", type="object", desc="返回数据")
     */
    public function list()
    {
        $robot_id = input('robot_id', 0, 'intval');
        $member_id = $this->request->uid;
        $robot = \app\common\model\Robot::where('id', $robot_id)
            ->where('member_id', $member_id)
            ->find();
        if(!$robot){
            return error('该机器人不属于你，非法请求！' );
        }
        $res = \app\common\model\RobotApi::where('robot_id', $robot_id)->select();
        return success('ok', $res);
    }

    /**
     * @Apidoc\Title("删除")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("id", type="int", require=true, desc="key_id")
     * @Apidoc\Param("robot_id", type="int", require=true, desc="机器人id")
     * @Apidoc\Returned("data", type="object", desc="返回数据")
     */
    public function delete()
    {
        $robot_id = input('robot_id', 0, 'intval');
        $member_id = $this->request->uid;
        $robot = \app\common\model\Robot::where('id', $robot_id)
            ->where('member_id', $member_id)
            ->find();
        if(!$robot){
            return error('该机器人不属于你，非法请求！' );
        }
        $event = \app\common\model\RobotApi::where('id', input('id', 0, 'intval'))
            ->where('robot_id', $robot_id)
            ->find();
        if(!$event){
            return error('该key不存在！');
        }
        $event->delete();
        return success();
    }


}